//
//  LimitFreeCtl.m
//  IFreeAppDemo
//
//  Created by qianfeng on 15/11/3.
//  Copyright © 2015年 qianfeng. All rights reserved.
//

#import "LimitFreeCtl.h"
#import "IFreeConnect.h"
#import "IFreeInterface.h"
#import "LimitFreeModel.h"
#import "MJRefresh.h"
#import "LimitCell.h"
#import "DetailViewCtl.h"
#import "FMDBManager.h"

@interface LimitFreeCtl ()<UITableViewDelegate,UITableViewDataSource,UISearchResultsUpdating,UISearchControllerDelegate>
@property (nonatomic,strong) UITableView * mTableView;
@property (nonatomic,strong) NSMutableArray * mDataArr;
// ios8 搜索用
@property (nonatomic,strong) NSMutableArray * mSearchArr;
@property (nonatomic,strong) UISearchController * searchCtl;
@property (nonatomic,strong) UITableViewController * searchTableViewCtl;
@property (nonatomic,assign) BOOL isSearch;
// 上下拉刷新Page
@property (nonatomic,assign) NSUInteger page;
// 上拉/下拉刷新标记位
@property (nonatomic,assign) BOOL isPull;

@end

@implementation LimitFreeCtl
- (NSMutableArray *)mDataArr
{
    if (_mDataArr == nil) {
        _mDataArr = [NSMutableArray array];
    }
    return _mDataArr;
}

- (UITableViewController *)searchTableViewCtl
{
    if (_searchTableViewCtl == nil) {
        _searchTableViewCtl = [[UITableViewController alloc] init];
        _searchTableViewCtl.tableView.delegate = self;
        _searchTableViewCtl.tableView.dataSource = self;
        
        [_searchTableViewCtl.tableView registerNib:[UINib nibWithNibName:@"LimitCell" bundle:nil] forCellReuseIdentifier:@"Cell"];
    }
    return _searchTableViewCtl;
}

- (UISearchController *)searchCtl
{
    if (_searchCtl == nil) {
        _searchCtl = [[UISearchController alloc] initWithSearchResultsController:self.searchTableViewCtl];
        _searchCtl.searchResultsUpdater = self;
        _searchCtl.delegate = self;
        // 搜索时不隐藏导航栏
        _searchCtl.hidesNavigationBarDuringPresentation = NO;
        self.mTableView.tableHeaderView = _searchCtl.searchBar;
    }
    return _searchCtl;
}

// 属性尽量使用懒加载方式
- (UITableView *)mTableView
{
    if (_mTableView == nil) {
        _mTableView = [[UITableView alloc] initWithFrame:CGRectMake(0, 0, self.view.bounds.size.width, self.view.bounds.size.height) style:UITableViewStylePlain];
        _mTableView.delegate = self;
        _mTableView.dataSource = self;
        [self.view addSubview:_mTableView];
        
        [_mTableView registerNib:[UINib nibWithNibName:@"LimitCell" bundle:nil] forCellReuseIdentifier:@"Cell"];
    }
    return _mTableView;
}

- (void)viewDidLoad {
    [super viewDidLoad];
    // Do any additional setup after loading the view.

    [self initUI];
    [self loadData];
    
    
    FMDBManager * manager = [FMDBManager shareInstance];
}

- (void)initUI
{
    // 默认情况下加载第一页
    self.page = 1;
    // searchBar 自适应
    [self.searchCtl.searchBar sizeToFit];
    
    __weak LimitFreeCtl * ctl = self;
    // 添加上下拉刷新
    [self.mTableView addLegendHeaderWithRefreshingBlock:^{
        ctl.page = 1;
        ctl.isPull = NO;
        [ctl loadData];
    }];
    
    [self.mTableView addLegendFooterWithRefreshingBlock:^{
        ctl.isPull = YES;
        ctl.page++;
        [ctl loadData];
    }];
}

- (void)loadData
{
    IFreeConnect * connect = [IFreeConnect shareInstance];
    NSString * url = [NSString stringWithFormat:self.url,self.page];
    // NSLog(@"url:%@",url);
    [connect limitFreeURL:url result:^(id data, NSError *error) {
        if (error == nil) {
            // 下拉刷新 清空数据源
            if (!self.isPull) {
                [self.mDataArr removeAllObjects];
            }
            [self.mDataArr addObjectsFromArray:data];
            
            // 复原上下拉刷新
            [self.mTableView.header endRefreshing];
            [self.mTableView.footer endRefreshing];
            [self.mTableView reloadData];
        }
    }];
}

- (void)loadSearchData
{
    IFreeConnect * connect = [IFreeConnect shareInstance];
    // URL 必须是SearchBar.text拼接而成的
    // 带中文的请求必须统一编码格式
    NSString * url = [NSString stringWithFormat:LimitSearchURL,self.searchCtl.searchBar.text];
    [connect limitSearchURL:[url stringByAddingPercentEscapesUsingEncoding:NSUTF8StringEncoding] result:^(id data, NSError *error) {
        // 强引用IFreeConnect中实例化的数组
        self.mSearchArr = data;
        [self.searchTableViewCtl.tableView reloadData];
    }];
}

#pragma mark - UITableViewDataSource
// 当前视图控制器上同时存在2个表格视图 self.mTableView  self.searchTableViewCtl.tableView
- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath
{
    LimitCell * cell = [tableView dequeueReusableCellWithIdentifier:@"Cell"];
    LimitFreeModel * m = self.isSearch?self.mSearchArr[indexPath.row]:self.mDataArr[indexPath.row];
    cell.model = m;
    return cell;
}

- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section
{
    return self.isSearch?self.mSearchArr.count:self.mDataArr.count;
}

- (CGFloat)tableView:(UITableView *)tableView heightForRowAtIndexPath:(NSIndexPath *)indexPath
{
    return 125;
}

- (void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath
{
    // 取消被选中
    [tableView deselectRowAtIndexPath:indexPath animated:YES];
    
    DetailViewCtl * ctl = [[DetailViewCtl alloc] init];
    ctl.applicationId = [self.mDataArr[indexPath.row] applicationId];
    [self.navigationController pushViewController:ctl animated:YES];
}

#pragma mark - UISearchResultsUpdating
- (void)updateSearchResultsForSearchController:(UISearchController *)searchController
{
//    NSLog(@"Search...");
    // 发搜索的网络请求 使用搜索数据刷新当前表格视图
    [self loadSearchData];
}

#pragma mark - UISearchBar处于编辑或者非编辑状态回调
- (void)didDismissSearchController:(UISearchController *)searchController
{
//    NSLog(@"非搜索状态");
    self.isSearch = NO;
}

- (void)didPresentSearchController:(UISearchController *)searchController
{
//    NSLog(@"搜索状态");
    self.isSearch = YES;
}

@end
